<template>
  <view class="ai-assistant">
    <!-- 聊天区域 -->
    <scroll-view class="chat-container" scroll-y="true" :scroll-top="scrollTop" scroll-with-animation>
      <view class="chat-list">
        <!-- 欢迎消息 -->
        <view class="message-item assistant-message" v-if="messages.length === 0">
          <view class="message-avatar">
            <text class="avatar-text">🤖</text>
          </view>
          <view class="message-content">
            <text class="message-text">您好！我是母婴助手。我可以帮您记录和查询宝宝的喂养数据，所有回答都基于真实的数据库记录。请告诉我您需要什么帮助！</text>
          </view>
        </view>

        <!-- 聊天消息 -->
        <view class="message-item" v-for="(message, index) in messages" :key="index" :class="message.role === 'user' ? 'user-message' : 'assistant-message'">
          <view class="message-avatar">
            <text class="avatar-text">{{ message.role === 'user' ? '👤' : '🤖' }}</text>
          </view>
          <view class="message-content">
            <text class="message-text">{{ message.content }}</text>
          </view>
        </view>

        <!-- 正在输入指示器 -->
        <view class="message-item assistant-message" v-if="isTyping">
          <view class="message-avatar">
            <text class="avatar-text">🤖</text>
          </view>
          <view class="message-content">
            <text class="message-text">{{ typingText }}</text>
            <text class="typing-cursor">|</text>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 输入区域 -->
    <view class="input-container">
      <view class="input-wrapper">
        <input class="message-input" type="text" v-model="inputText" placeholder="请输入您的问题..." @confirm="sendMessage" @input="handleInput" :disabled="isTyping" confirm-type="send" maxlength="500" />
        <button class="send-button" @click="sendMessage" :disabled="isTyping || isExecutingTool || !inputText.trim()">
          <text class="send-text">{{ getButtonText() }}</text>
        </button>
      </view>
    </view>
  </view>
</template>

<script>
// 导入配置
import config from '@/config.js'; // 本地配置文件，如果不存在会回退到config.example.js
// 获取Deepseek配置
const deepseekConfig = config.deepseek || {
  apiKey: '', 
  apiUrl: '',
  model: 'deepseek-chat',
  temperature: 0.7,
  max_tokens: 1000
};

export default {
  data() {
    return {
      messages: [],
      inputText: '',
      isTyping: false,
      typingText: '',
      scrollTop: 0,
      // 从配置中获取API设置
      apiKey: deepseekConfig.apiKey,
      apiUrl: deepseekConfig.apiUrl,
      model: deepseekConfig.model,
      temperature: deepseekConfig.temperature,
      max_tokens: deepseekConfig.max_tokens,
      isExecutingTool: false,

      // 删除确认和撤销功能状态
      pendingDeleteAction: null, // 待确认的删除操作
      lastDeletedRecords: null, // 最近删除的记录（用于撤销）
      deleteBackupTimestamp: null, // 删除时间戳
      isWaitingConfirmation: false, // 是否等待用户确认
      undoTimeLimit: 5 * 60 * 1000 // 撤销时间限制（5分钟）
    }
  },

  onLoad() {
    this.setStatusBar()
    this.checkNetworkStatus()
    this.validateConfig()
    console.log('页面加载完成，输入框初始值：', this.inputText)
  },

  methods: {
    // 验证配置
    validateConfig() {
      try {
        // 验证配置是否正确加载
        if (!this.apiKey || !this.apiUrl) {
          uni.showToast({
            title: 'API配置未设置',
            icon: 'error'
          });
          console.error('请设置config.js中的deepseek.apiKey和deepseek.apiUrl');
        } else {
          console.log('API配置已正确加载');
        }
      } catch (error) {
        uni.showToast({
          title: '配置加载失败',
          icon: 'error'
        });
        console.error('配置验证失败:', error);
      }
    },
    
    setStatusBar() {
      uni.setNavigationBarTitle({
        title: '母婴助手'
      })
    },

    checkNetworkStatus() {
      uni.getNetworkType({
        success: (res) => {
          console.log('网络类型：', res.networkType)
          if (res.networkType === 'none') {
            uni.showToast({
              title: '网络连接异常',
              icon: 'error'
            })
          }
        }
      })
    },

    handleInput(e) {
      // 处理输入事件
      this.inputText = e.detail.value
      // console.log('输入内容：', this.inputText)
    },

    async sendMessage() {
      if (!this.inputText.trim() || this.isTyping) return

      const networkInfo = await new Promise((resolve) => {
        uni.getNetworkType({
          success: resolve,
          fail: () => resolve({ networkType: 'none' })
        })
      })

      if (networkInfo.networkType === 'none') {
        uni.showToast({
          title: '网络连接异常，请检查网络',
          icon: 'error',
          duration: 2000
        })
        return
      }

      const userMessage = this.inputText.trim()
      this.inputText = ''

      this.messages.push({
        role: 'user',
        content: userMessage
      })

      this.scrollToBottom()
      await this.callDeepSeekAPI(userMessage)
    },

    async callDeepSeekAPI(userMessage) {
      this.isTyping = true
      this.typingText = ''

      // 验证API配置
      if (!this.apiKey || !this.apiUrl) {
        console.error('API配置不完整，无法调用DeepSeek');
        this.isTyping = false;
        this.messages.push({
          role: 'assistant',
          content: '抱歉，系统配置不正确，暂时无法提供服务。'
        });
        return;
      }

      try {
        console.log('分析用户意图...')
        const intent = await this.analyzeUserIntent(userMessage)
        console.log('用户意图：', intent)

        let toolResult = null
        let finalPrompt = userMessage

        // 如果需要工具调用，执行工具
        if (intent.action !== 'chat_only' && intent.confidence > 0.5) {
          console.log('执行工具调用...', intent.action)

          await this.typewriterEffect('正在为您处理...')
          this.typingText = ''

          toolResult = await this.executeTool(intent)
          console.log('工具执行结果：', toolResult)

          // 验证工具调用是否成功
          if (!toolResult || !toolResult.success) {
            const errorMessage = '抱歉，无法获取数据，请稍后重试。'
            await this.typewriterEffect(errorMessage)
            this.messages.push({
              role: 'assistant',
              content: errorMessage
            })
            return
          }

          // 构建包含真实数据的提示
          finalPrompt = this.buildDataPrompt(userMessage, intent, toolResult)
        }

        // 生成AI回答
        const messageHistory = [
          {
            role: 'system',
            content: `你是一个专业的母婴护理助手，严格基于真实数据库数据回答用户问题。

**绝对严格遵守：**
1. 你只能基于工具调用返回的真实数据库数据进行回答
2. 绝对不能编造、猜测或提供任何未在数据库中存在的数据
3. 如果没有工具调用结果，只能提供一般性建议，不能提供具体数据
4. 所有具体的时间、奶量、次数都必须来自真实的数据库查询结果

**回答格式要求：**
- 查询操作：逐条列出所有真实记录，明确说明"根据数据库查询结果"
- 记录操作：确认具体保存的数据
- 无数据时：明确说明"数据库中暂无相关记录"

使用中文回答，语气温和专业。`
          },
          ...this.messages.slice(-5),
          {
            role: 'user',
            content: finalPrompt
          }
        ]

        const response = await uni.request({
          url: this.apiUrl,
          method: 'POST',
          timeout: 30000,
          header: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${this.apiKey}`
          },
          data: {
            model: this.model,
            messages: messageHistory,
            temperature: this.temperature,
            max_tokens: this.max_tokens
          }
        })

        if (response.statusCode === 200 && response.data.choices?.length > 0) {
          const assistantMessage = response.data.choices[0].message.content
          await this.typewriterEffect(assistantMessage)
          this.messages.push({
            role: 'assistant',
            content: assistantMessage
          })
        } else {
          throw new Error('API响应异常')
        }
      } catch (error) {
        console.error('API调用失败:', error)
        const errorMessage = '抱歉，我现在无法回答您的问题。请稍后重试。'
        await this.typewriterEffect(errorMessage)
        this.messages.push({
          role: 'assistant',
          content: errorMessage
        })
      } finally {
        this.isTyping = false
        this.typingText = ''
        this.scrollToBottom()
      }
    },

    buildDataPrompt(userMessage, intent, toolResult) {
      let dataDescription = ''

      if (intent.action === 'get_feeding_records') {
        const records = toolResult.data || []
        if (records.length === 0) {
          dataDescription = '数据库查询结果：暂无记录'
        } else {
          dataDescription = `数据库查询结果：找到${
            records.length
          }条记录\n${records
            .map(
              (record, index) =>
                `${index + 1}. 日期：${record.date}，时间：${
                  record.time
                }，奶量：${record.amount}毫升，类型：${this.getFeedingTypeText(
                  record.feeding_type
                )}${record.notes ? '，备注：' + record.notes : ''}`
            )
            .join('\n')}`
        }
      } else if (intent.action === 'get_feeding_statistics') {
        const stats = toolResult.data || {}
        dataDescription = `数据库统计结果：\n- 总奶量：${
          stats.totalAmount || 0
        }毫升\n- 平均奶量：${stats.avgAmount || 0}毫升\n- 喝奶次数：${
          stats.recordCount || 0
        }次`
      } else if (intent.action === 'record_feeding') {
        const record = toolResult.data || {}
        dataDescription = `记录成功，已保存到数据库：\n- 时间：${
          record.time
        }\n- 奶量：${record.amount}毫升\n- 类型：${this.getFeedingTypeText(
          record.feeding_type
        )}`
      } else if (intent.action === 'delete_feeding_record') {
        const deleteData = toolResult.data || {}

        if (toolResult.requiresConfirmation) {
          // 需要确认的删除操作
          const previewRecords = deleteData.records || []
          dataDescription = `删除预览：找到${
            deleteData.previewCount
          }条符合条件的记录\n预览清单：\n${previewRecords
            .map(
              (record, index) =>
                `${index + 1}. 日期：${record.date}，时间：${
                  record.time
                }，奶量：${record.amount}毫升，类型：${this.getFeedingTypeText(
                  record.feeding_type
                )}${record.notes ? '，备注：' + record.notes : ''}`
            )
            .join(
              '\n'
            )}\n\n请回复"确认删除"来执行删除，或回复"取消"来保留记录。`
        } else if (toolResult.hasSuggestions) {
          // 智能建议
          const suggestions = deleteData.suggestions || []
          if (suggestions.length > 0) {
            dataDescription = `智能建议：没有找到精确匹配的记录，但发现${
              suggestions.length
            }条相似记录\n建议清单：\n${suggestions
              .map(
                (record, index) =>
                  `${index + 1}. 日期：${record.date}，时间：${
                    record.time
                  }，奶量：${
                    record.amount
                  }毫升，类型：${this.getFeedingTypeText(
                    record.feeding_type
                  )}，匹配度：${record.matchScore}%${
                    record.notes ? '，备注：' + record.notes : ''
                  }`
              )
              .join('\n')}\n\n请说"删除第X条"来选择要删除的记录。`
          } else {
            dataDescription = '删除操作结果：没有找到符合条件的记录'
          }
        } else if (deleteData.deletedCount !== undefined) {
          // 实际删除结果
          if (deleteData.deletedCount === 0) {
            dataDescription = '删除操作结果：没有找到符合条件的记录'
          } else {
            const deletedRecords = deleteData.records || []
            dataDescription = `删除操作结果：成功删除${
              deleteData.deletedCount
            }条记录\n删除的记录：\n${deletedRecords
              .map(
                (record, index) =>
                  `${index + 1}. 日期：${record.date}，时间：${
                    record.time
                  }，奶量：${
                    record.amount
                  }毫升，类型：${this.getFeedingTypeText(record.feeding_type)}${
                    record.notes ? '，备注：' + record.notes : ''
                  }`
              )
              .join('\n')}`

            if (deleteData.failedCount > 0) {
              dataDescription += `\n注意：有${deleteData.failedCount}条记录删除失败`
            }

            if (deleteData.canUndo) {
              dataDescription += `\n\n💡 如需撤销删除，请在${
                deleteData.undoTimeLimit / 60
              }分钟内说"撤销删除"`
            }
          }
        }
      } else if (intent.action === 'confirm_action') {
        const confirmData = toolResult.data || {}
        if (confirmData.deletedCount !== undefined) {
          const deletedRecords = confirmData.records || []
          dataDescription = `确认删除结果：成功删除${
            confirmData.deletedCount
          }条记录\n删除的记录：\n${deletedRecords
            .map(
              (record, index) =>
                `${index + 1}. 日期：${record.date}，时间：${
                  record.time
                }，奶量：${record.amount}毫升，类型：${this.getFeedingTypeText(
                  record.feeding_type
                )}${record.notes ? '，备注：' + record.notes : ''}`
            )
            .join('\n')}`

          if (confirmData.canUndo) {
            dataDescription += `\n\n💡 如需撤销删除，请在${
              confirmData.undoTimeLimit / 60
            }分钟内说"撤销删除"`
          }
        }
      } else if (intent.action === 'cancel_action') {
        const cancelData = toolResult.data || {}
        dataDescription = `取消操作结果：已取消删除操作，${cancelData.cancelledCount}条记录已保留`
      } else if (intent.action === 'undo_delete') {
        const undoData = toolResult.data || {}
        if (undoData.restoredCount !== undefined) {
          dataDescription = `撤销删除结果：成功恢复${
            undoData.restoredCount
          }条记录${
            undoData.failedCount > 0 ? `，失败${undoData.failedCount}条` : ''
          }`
        }
      }

      return `用户请求：${userMessage}

${dataDescription}

请严格基于以上真实数据库结果回答用户，不要添加任何未在结果中显示的信息。`
    },

    getFeedingTypeText(type) {
      const typeMap = {
        bottle_breast: '母乳',
        bottle_formula: '奶粉',
        direct: '亲喂'
      }
      return typeMap[type] || type
    },

    async analyzeUserIntent(userMessage) {
      try {
        const response = await uni.request({
          url: this.apiUrl,
          method: 'POST',
          timeout: 30000,
          header: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${this.apiKey}`
          },
          data: {
            model: this.model,
            messages: [
              {
                role: 'system',
                content: `分析用户意图，返回JSON格式。严格遵守以下参数格式要求：

操作类型：
- record_feeding：记录喝奶（关键词：记录、喝了、喝奶、添加）
- get_feeding_records：查询记录（关键词：查询、查看、所有、当前、全部、历史、记录列表）
- get_feeding_statistics：统计（关键词：统计、总计、汇总、一共）
- delete_feeding_record：删除记录（关键词：删除、删掉、移除）
- undo_delete：撤销删除（关键词：撤销、恢复、取消删除、后悔了）
- confirm_action：确认操作（关键词：确认、好的、是的、执行）
- cancel_action：取消操作（关键词：取消、不要、算了）
- chat_only：咨询问题

参数格式严格要求：
1. date：必须是YYYY-MM-DD格式，禁止使用"today"、"昨天"等词汇
   - "今天" → 使用当前日期：${new Date().toISOString().split('T')[0]}
   - "昨天" → 使用昨天日期：${
     new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString().split('T')[0]
   }
   - 如果没有指定日期，设置为null

2. time：必须是HH:MM格式（24小时制）
   - "10:30"、"10点30分"、"上午10点半" → "10:30"
   - "下午2点" → "14:00"
   - 如果没有指定时间，设置为null

3. amount：必须是纯数字，不带单位
   - "120ml"、"120毫升" → 120
   - "一百二十" → 120

4. feeding_type：严格使用以下值
   - "母乳"、"喝母乳" → "bottle_breast"
   - "奶粉"、"喝奶粉" → "bottle_formula" 
   - "亲喂"、"直接喂" → "direct"
   - 默认："bottle_breast"

5. notes：字符串，可为空

6. 删除操作特殊参数：
   - delete_type：删除类型（"exact_match"、"time_range"、"recent_count"）
   - recent_count：最近几条（"删除最近2条" → 2）
   - time_start、time_end：时间范围（"删除10点到11点" → "10:00", "11:00"）
   
重要：识别模糊时间表达
   - "10点左右"、"大概10点"、"10点半左右" → time_range（前后15分钟）
   - "准确10:30"、"正好10点" → exact_match

只返回JSON，格式：{"action":"类型","parameters":{"time":"HH:MM或null","amount":数字或null,"feeding_type":"类型","date":"YYYY-MM-DD或null","notes":"备注","delete_type":"删除类型","recent_count":数字,"time_start":"HH:MM","time_end":"HH:MM"},"confidence":0.8}

示例：
用户："今天10:30宝宝喝了120ml母乳"
返回：{"action":"record_feeding","parameters":{"time":"10:30","amount":120,"feeding_type":"bottle_breast","date":"${
                  new Date().toISOString().split('T')[0]
                }","notes":""},"confidence":0.9}

用户："查看今天的喝奶记录"
返回：{"action":"get_feeding_records","parameters":{"date":"${
                  new Date().toISOString().split('T')[0]
                }"},"confidence":0.9}

用户："删除今天10:30的记录"
返回：{"action":"delete_feeding_record","parameters":{"date":"${
                  new Date().toISOString().split('T')[0]
                }","time":"10:30","delete_type":"exact_match"},"confidence":0.9}

用户："删除最近2条记录"
返回：{"action":"delete_feeding_record","parameters":{"delete_type":"recent_count","recent_count":2},"confidence":0.9}

用户："删除今天10点到11点之间的记录"
返回：{"action":"delete_feeding_record","parameters":{"date":"${
                  new Date().toISOString().split('T')[0]
                }","delete_type":"time_range","time_start":"10:00","time_end":"11:00"},"confidence":0.9}

用户："删除11点左右那条记录"
返回：{"action":"delete_feeding_record","parameters":{"date":"${
                  new Date().toISOString().split('T')[0]
                }","delete_type":"time_range","time_start":"10:45","time_end":"11:15"},"confidence":0.9}`
              },
              {
                role: 'user',
                content: userMessage
              }
            ],
            temperature: 0.01,
            max_tokens: 500
          }
        })

        if (response.statusCode === 200 && response.data.choices?.length > 0) {
          const content = response.data.choices[0].message.content.trim()
          console.log('意图分析原始结果：', content)

          // 提取JSON
          let jsonContent = content
          if (content.startsWith('```json') && content.endsWith('```')) {
            jsonContent = content
              .replace(/^```json\s*/, '')
              .replace(/\s*```$/, '')
          } else if (content.startsWith('```') && content.endsWith('```')) {
            jsonContent = content.replace(/^```\s*/, '').replace(/\s*```$/, '')
          }

          const intent = JSON.parse(jsonContent)
          console.log('解析的意图：', intent)
          return intent
        }

        return { action: 'chat_only', confidence: 1.0 }
      } catch (error) {
        console.error('意图分析失败：', error)
        return { action: 'chat_only', confidence: 1.0 }
      }
    },

    async executeTool(intent) {
      this.isExecutingTool = true
      console.log('执行工具：', intent.action)

      try {
        // 验证和格式化参数
        const validatedParameters = this.validateAndFormatParameters(
          intent.action,
          intent.parameters
        )

        switch (intent.action) {
          case 'record_feeding':
            return await this.recordFeeding(validatedParameters)
          case 'get_feeding_records':
            return await this.getFeedingRecords(validatedParameters?.date)
          case 'get_feeding_statistics':
            return await this.getFeedingStatistics(validatedParameters?.date)
          case 'delete_feeding_record':
            return await this.deleteFeedingRecord(validatedParameters)
          case 'undo_delete':
            return await this.undoDelete()
          case 'confirm_action':
            return await this.confirmPendingAction()
          case 'cancel_action':
            return await this.cancelPendingAction()
          default:
            return { success: false, message: '未知操作类型' }
        }
      } catch (error) {
        console.error('工具执行失败：', error)
        return { success: false, message: error.message }
      } finally {
        this.isExecutingTool = false
      }
    },

    // 新增：参数验证和格式化方法
    validateAndFormatParameters(action, parameters) {
      if (!parameters) {
        parameters = {}
      }

      const today = new Date()
      const todayStr = today.toISOString().split('T')[0]
      const nowTimeStr = `${today
        .getHours()
        .toString()
        .padStart(2, '0')}:${today.getMinutes().toString().padStart(2, '0')}`

      // 日期格式验证和转换
      if (parameters.date) {
        // 处理相对日期表达
        if (parameters.date === 'today' || parameters.date === '今天') {
          parameters.date = todayStr
        } else if (
          parameters.date === 'yesterday' ||
          parameters.date === '昨天'
        ) {
          parameters.date = new Date(Date.now() - 24 * 60 * 60 * 1000)
            .toISOString()
            .split('T')[0]
        } else {
          // 验证日期格式是否为YYYY-MM-DD
          const dateRegex = /^\d{4}-\d{2}-\d{2}$/
          if (!dateRegex.test(parameters.date)) {
            console.warn('日期格式不正确，使用今天日期:', parameters.date)
            parameters.date = todayStr
          }
        }
      }

      // 时间格式验证
      if (parameters.time) {
        const timeRegex = /^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$/
        if (!timeRegex.test(parameters.time)) {
          console.warn('时间格式不正确，使用当前时间:', parameters.time)
          parameters.time = nowTimeStr
        }
      }

      // 奶量验证
      if (parameters.amount) {
        const amount = parseInt(parameters.amount)
        if (isNaN(amount) || amount <= 0 || amount > 500) {
          console.warn('奶量参数不正确:', parameters.amount)
          throw new Error('奶量必须是1-500之间的数字')
        }
        parameters.amount = amount
      }

      // 喂养类型验证
      if (parameters.feeding_type) {
        const validTypes = ['bottle_breast', 'bottle_formula', 'direct']
        if (!validTypes.includes(parameters.feeding_type)) {
          console.warn('喂养类型不正确，使用默认值:', parameters.feeding_type)
          parameters.feeding_type = 'bottle_breast'
        }
      }

      // 根据不同操作类型进行特定验证
      switch (action) {
        case 'record_feeding':
          // 记录操作必须有奶量
          if (!parameters.amount) {
            throw new Error('记录喝奶必须提供奶量')
          }
          // 设置默认值
          if (!parameters.date) parameters.date = todayStr
          if (!parameters.time) parameters.time = nowTimeStr
          if (!parameters.feeding_type)
            parameters.feeding_type = 'bottle_breast'
          if (!parameters.notes) parameters.notes = ''
          break

        case 'get_feeding_records':
          // 查询操作如果没有日期，则查询所有记录
          if (!parameters.date) {
            console.log('未指定日期，将查询所有记录')
          }
          break

        case 'get_feeding_statistics':
          // 统计操作如果没有日期，使用今天
          if (!parameters.date) {
            parameters.date = todayStr
          }
          break

        case 'delete_feeding_record':
          // 删除操作参数验证
          if (!parameters.delete_type) {
            throw new Error('删除操作必须指定删除类型')
          }

          const validDeleteTypes = ['exact_match', 'time_range', 'recent_count']
          if (!validDeleteTypes.includes(parameters.delete_type)) {
            throw new Error('删除类型不正确')
          }

          // 根据删除类型验证必要参数
          switch (parameters.delete_type) {
            case 'exact_match':
              if (!parameters.date) parameters.date = todayStr
              if (!parameters.time) {
                throw new Error('精确匹配删除必须提供时间')
              }
              break

            case 'time_range':
              if (!parameters.date) parameters.date = todayStr
              if (!parameters.time_start || !parameters.time_end) {
                throw new Error('时间范围删除必须提供开始和结束时间')
              }
              // 验证时间范围格式
              const timeRegex = /^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$/
              if (
                !timeRegex.test(parameters.time_start) ||
                !timeRegex.test(parameters.time_end)
              ) {
                throw new Error('时间范围格式不正确')
              }
              break

            case 'recent_count':
              if (!parameters.recent_count || isNaN(parameters.recent_count)) {
                throw new Error('最近记录删除必须提供有效的数量')
              }
              parameters.recent_count = parseInt(parameters.recent_count)
              if (
                parameters.recent_count <= 0 ||
                parameters.recent_count > 10
              ) {
                throw new Error('删除数量必须在1-10之间')
              }
              break
          }
          break
      }

      console.log('验证后的参数：', parameters)
      return parameters
    },

    async recordFeeding(parameters) {
      try {
        if (!parameters || !parameters.amount) {
          return { success: false, message: '缺少必要参数' }
        }

        const today = new Date()
        const recordData = {
          date: parameters.date || today.toISOString().split('T')[0],
          time:
            parameters.time ||
            `${today.getHours().toString().padStart(2, '0')}:${today
              .getMinutes()
              .toString()
              .padStart(2, '0')}`,
          amount: parseInt(parameters.amount),
          feeding_type: parameters.feeding_type || 'bottle_breast',
          notes: parameters.notes || '',
          source: 'ai_assistant'
        }

        console.log('记录数据：', recordData)

        const response = await uniCloud.callFunction({
          name: 'milk-record-service',
          data: {
            action: 'add',
            data: recordData
          }
        })

        console.log('云函数响应：', response)

        return {
          success: response.result.success,
          data: recordData,
          message: response.result.message || '记录成功'
        }
      } catch (error) {
        console.error('记录失败：', error)
        return { success: false, message: '记录失败：' + error.message }
      }
    },

    async getFeedingRecords(date) {
      try {
        let response

        if (!date) {
          console.log('查询所有记录...')
          response = await uniCloud.callFunction({
            name: 'milk-record-service',
            data: { action: 'getAll' }
          })
        } else {
          console.log('查询指定日期记录：', date)
          response = await uniCloud.callFunction({
            name: 'milk-record-service',
            data: { action: 'get', data: { date } }
          })
        }

        console.log('查询响应：', response)

        return {
          success: response.result.success,
          data: response.result.data,
          message: response.result.message || '查询成功'
        }
      } catch (error) {
        console.error('查询失败：', error)
        return { success: false, message: '查询失败：' + error.message }
      }
    },

    async getFeedingStatistics(date) {
      try {
        const targetDate = date || new Date().toISOString().split('T')[0]

        const response = await uniCloud.callFunction({
          name: 'milk-record-service',
          data: {
            action: 'getStatistics',
            data: { statDate: targetDate }
          }
        })

        return {
          success: response.result.success,
          data: response.result.data,
          message: response.result.message || '统计成功'
        }
      } catch (error) {
        console.error('统计失败：', error)
        return { success: false, message: '统计失败：' + error.message }
      }
    },

    async deleteFeedingRecord(parameters) {
      try {
        console.log('开始删除操作，参数：', parameters)

        // 第一步：查找要删除的记录
        const findParams = this.buildFindParameters(parameters)
        const findResponse = await uniCloud.callFunction({
          name: 'milk-record-service',
          data: {
            action: 'findRecords',
            data: findParams
          }
        })

        if (!findResponse.result.success) {
          return {
            success: false,
            message: '查找记录失败：' + findResponse.result.message
          }
        }

        const foundRecords = findResponse.result.data.records || []
        console.log('找到记录：', foundRecords)

        if (foundRecords.length === 0) {
          // 没找到记录，尝试智能建议
          return await this.findSimilarRecordsForSuggestion(parameters)
        }

        // 第二步：保存待确认的删除操作，不立即执行
        this.pendingDeleteAction = {
          type: 'delete',
          parameters: parameters,
          foundRecords: foundRecords,
          recordIds: foundRecords.map((record) => record._id)
        }
        this.isWaitingConfirmation = true

        console.log('等待用户确认删除')

        return {
          success: true,
          requiresConfirmation: true,
          data: {
            previewCount: foundRecords.length,
            records: foundRecords.map((record) => ({
              date: record.date,
              time: record.time,
              amount: record.amount,
              feeding_type: record.feeding_type,
              notes: record.notes
            }))
          },
          message: `找到${foundRecords.length}条符合条件的记录，需要确认删除`
        }
      } catch (error) {
        console.error('删除操作失败：', error)
        return {
          success: false,
          message: '删除操作失败：' + error.message
        }
      }
    },

    async findSimilarRecordsForSuggestion(parameters) {
      try {
        // 当精确匹配失败时，尝试查找相似记录
        const suggestionParams = {
          date: parameters.date,
          time: parameters.time || parameters.time_start,
          timeRange: 60 // 前后1小时
        }

        const suggestionResponse = await uniCloud.callFunction({
          name: 'milk-record-service',
          data: {
            action: 'findSimilarRecords',
            data: suggestionParams
          }
        })

        if (!suggestionResponse.result.success) {
          return {
            success: true,
            data: { suggestions: [], targetTime: suggestionParams.time },
            message: '没有找到符合条件的记录，也没有相似的建议'
          }
        }

        const suggestions = suggestionResponse.result.data.suggestions || []

        return {
          success: true,
          hasSuggestions: true,
          data: {
            suggestions: suggestions,
            targetTime: suggestionParams.time,
            searchRange: suggestionResponse.result.data.searchRange
          },
          message:
            suggestions.length > 0
              ? `没有找到精确匹配的记录，但发现${suggestions.length}条相似记录`
              : '没有找到符合条件的记录'
        }
      } catch (error) {
        console.error('智能建议查询失败：', error)
        return {
          success: true,
          data: { suggestions: [] },
          message: '没有找到符合条件的记录'
        }
      }
    },

    async confirmPendingAction() {
      try {
        if (!this.pendingDeleteAction || !this.isWaitingConfirmation) {
          return {
            success: false,
            message: '没有待确认的操作'
          }
        }

        const action = this.pendingDeleteAction
        console.log('确认执行删除操作')

        // 执行实际的删除操作
        const deleteResponse = await uniCloud.callFunction({
          name: 'milk-record-service',
          data: {
            action: 'batchDelete',
            data: { ids: action.recordIds }
          }
        })

        if (!deleteResponse.result.success) {
          return {
            success: false,
            message: '删除记录失败：' + deleteResponse.result.message
          }
        }

        const deleteResult = deleteResponse.result.data
        console.log('删除结果：', deleteResult)

        // 保存删除的记录以供撤销
        this.lastDeletedRecords = action.foundRecords
        this.deleteBackupTimestamp = Date.now()

        // 清除待确认状态
        this.pendingDeleteAction = null
        this.isWaitingConfirmation = false

        return {
          success: true,
          data: {
            deletedCount: deleteResult.successCount,
            failedCount: deleteResult.failCount,
            totalProcessed: deleteResult.totalProcessed,
            records: action.foundRecords.map((record) => ({
              date: record.date,
              time: record.time,
              amount: record.amount,
              feeding_type: record.feeding_type,
              notes: record.notes
            })),
            canUndo: true,
            undoTimeLimit: this.undoTimeLimit / 1000 // 转换为秒
          },
          message: `已确认删除${deleteResult.successCount}条记录${
            deleteResult.failCount > 0
              ? `，失败${deleteResult.failCount}条`
              : ''
          }。可在${this.undoTimeLimit / 60000}分钟内撤销删除。`
        }
      } catch (error) {
        console.error('确认删除操作失败：', error)
        return {
          success: false,
          message: '确认删除操作失败：' + error.message
        }
      }
    },

    async cancelPendingAction() {
      if (!this.pendingDeleteAction || !this.isWaitingConfirmation) {
        return {
          success: false,
          message: '没有待取消的操作'
        }
      }

      const recordCount = this.pendingDeleteAction.foundRecords.length

      // 清除待确认状态
      this.pendingDeleteAction = null
      this.isWaitingConfirmation = false

      return {
        success: true,
        data: { cancelledCount: recordCount },
        message: `已取消删除操作，${recordCount}条记录已保留`
      }
    },

    async undoDelete() {
      try {
        if (!this.lastDeletedRecords || !this.deleteBackupTimestamp) {
          return {
            success: false,
            message: '没有可撤销的删除操作'
          }
        }

        // 检查是否超时
        const now = Date.now()
        if (now - this.deleteBackupTimestamp > this.undoTimeLimit) {
          this.lastDeletedRecords = null
          this.deleteBackupTimestamp = null
          return {
            success: false,
            message: '撤销操作已超时，无法恢复记录'
          }
        }

        console.log('执行撤销删除操作')

        // 调用恢复接口
        const restoreResponse = await uniCloud.callFunction({
          name: 'milk-record-service',
          data: {
            action: 'restoreRecords',
            data: { records: this.lastDeletedRecords }
          }
        })

        if (!restoreResponse.result.success) {
          return {
            success: false,
            message: '恢复记录失败：' + restoreResponse.result.message
          }
        }

        const restoreResult = restoreResponse.result.data
        console.log('恢复结果：', restoreResult)

        // 清除撤销数据
        const restoredCount = restoreResult.successCount
        this.lastDeletedRecords = null
        this.deleteBackupTimestamp = null

        return {
          success: true,
          data: {
            restoredCount: restoredCount,
            failedCount: restoreResult.failCount,
            totalProcessed: restoreResult.totalProcessed
          },
          message: `已成功恢复${restoredCount}条记录${
            restoreResult.failCount > 0
              ? `，失败${restoreResult.failCount}条`
              : ''
          }`
        }
      } catch (error) {
        console.error('撤销删除失败：', error)
        return {
          success: false,
          message: '撤销删除失败：' + error.message
        }
      }
    },

    buildFindParameters(deleteParams) {
      const findParams = {}

      switch (deleteParams.delete_type) {
        case 'exact_match':
          // 精确匹配：按日期和时间查找
          findParams.date = deleteParams.date
          findParams.exactTime = deleteParams.time
          if (deleteParams.amount) {
            findParams.amount = deleteParams.amount
          }
          if (deleteParams.feeding_type) {
            findParams.feedingType = deleteParams.feeding_type
          }
          break

        case 'time_range':
          // 时间范围：在指定时间段内查找
          findParams.date = deleteParams.date
          findParams.timeRange = {
            start: deleteParams.time_start,
            end: deleteParams.time_end
          }
          break

        case 'recent_count':
          // 最近记录：按创建时间倒序查找
          findParams.limit = deleteParams.recent_count
          findParams.sortBy = 'create_time'
          findParams.sortOrder = 'desc'
          // 如果指定了日期，则只在该日期内查找
          if (deleteParams.date) {
            findParams.date = deleteParams.date
          }
          break
      }

      console.log('构建的查找参数：', findParams)
      return findParams
    },

    async typewriterEffect(text) {
      return new Promise((resolve) => {
        let index = 0
        const typingSpeed = 50

        const typeNextChar = () => {
          if (index < text.length) {
            this.typingText += text[index]
            index++
            this.scrollToBottom()
            setTimeout(typeNextChar, typingSpeed)
          } else {
            resolve()
          }
        }

        typeNextChar()
      })
    },

    scrollToBottom() {
      this.$nextTick(() => {
        this.scrollTop = 999999
      })
    },

    getButtonText() {
      if (this.isExecutingTool) {
        return '执行中...'
      } else if (this.isTyping) {
        return '发送中...'
      } else {
        return '发送'
      }
    }
  }
}
</script>

<style scoped>
.ai-assistant {
  display: flex;
  flex-direction: column;
  height: 100vh;
  width: 100vw;
  background: linear-gradient(160deg, #1c1d30 0%, #14152a 100%); /* 渐变背景 */
  overflow-x: hidden;
  box-sizing: border-box;
  position: relative;
}

/* 添加背景装饰元素 */
.ai-assistant::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 250rpx;
  background: linear-gradient(180deg, rgba(255, 107, 157, 0.2) 0%, rgba(0, 0, 0, 0) 100%);
  z-index: 0;
  opacity: 0.5;
}

.ai-assistant::after {
  content: "";
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 400rpx;
  background: linear-gradient(0deg, rgba(25, 26, 48, 0.9) 0%, rgba(0, 0, 0, 0) 100%);
  z-index: 0;
  pointer-events: none;
}

.chat-container {
  flex: 1;
  margin-top: 30rpx;
  margin-bottom: 140rpx;
  padding: 30rpx 40rpx;
  width: 100%;
  overflow-x: hidden;
  box-sizing: border-box;
  position: relative;
  z-index: 1;
  -webkit-overflow-scrolling: touch; /* 改善iOS滚动体验 */
}

.chat-list {
  display: flex;
  flex-direction: column;
  gap: 30rpx;
  width: 100%;
  overflow-x: hidden;
  box-sizing: border-box;
  padding: 20rpx 0;
}

.message-item {
  display: flex;
  align-items: flex-start;
  gap: 20rpx;
  max-width: 85%;
  width: fit-content;
  box-sizing: border-box;
  transition: all 0.3s ease;
  animation: fadeIn 0.3s ease-out forwards;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.user-message {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.assistant-message {
  align-self: flex-start;
}

.message-avatar {
  width: 90rpx;
  height: 90rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, rgba(255, 107, 157, 0.9) 0%, rgba(255, 105, 180, 0.7) 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  box-shadow: 0 8rpx 25rpx rgba(255, 66, 129, 0.3);
  border: 2rpx solid rgba(255, 255, 255, 0.2);
  transform: translateZ(0);
  overflow: hidden;
  position: relative;
}

.message-avatar::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 50%;
  background: rgba(255, 255, 255, 0.2);
  border-bottom-right-radius: 50%;
  border-bottom-left-radius: 50%;
}

.user-message .message-avatar {
  background: linear-gradient(135deg, rgba(30, 144, 255, 0.9) 0%, rgba(0, 120, 212, 0.7) 100%);
  box-shadow: 0 8rpx 25rpx rgba(0, 120, 212, 0.3);
}

.avatar-text {
  font-size: 38rpx;
  color: #fff;
  text-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.3);
  position: relative;
  z-index: 1;
}

.message-content {
  background: rgba(255, 255, 255, 0.08);
  padding: 25rpx 30rpx;
  border-radius: 30rpx;
  box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.15);
  position: relative;
  word-wrap: break-word;
  word-break: break-word;
  overflow-wrap: break-word;
  max-width: 100%;
  box-sizing: border-box;
  border: 1rpx solid rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
}

/* 添加消息气泡尖角 */
.assistant-message .message-content::before {
  content: "";
  position: absolute;
  left: -12rpx;
  top: 24rpx;
  width: 24rpx;
  height: 24rpx;
  background: rgba(255, 255, 255, 0.08);
  border-left: 1rpx solid rgba(255, 255, 255, 0.1);
  border-bottom: 1rpx solid rgba(255, 255, 255, 0.1);
  transform: rotate(45deg);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
}

.user-message .message-content::before {
  content: "";
  position: absolute;
  right: -12rpx;
  top: 24rpx;
  width: 24rpx;
  height: 24rpx;
  background: rgba(30, 144, 255, 0.25);
  border-right: 1rpx solid rgba(30, 144, 255, 0.3);
  border-top: 1rpx solid rgba(30, 144, 255, 0.3);
  transform: rotate(45deg);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
}

.user-message .message-content {
  background: rgba(30, 144, 255, 0.25);
  border: 1rpx solid rgba(30, 144, 255, 0.3);
}

.message-text {
  font-size: 30rpx;
  line-height: 1.7;
  color: rgba(255, 255, 255, 0.95);
  word-wrap: break-word;
  word-break: break-word;
  overflow-wrap: break-word;
  white-space: pre-wrap;
  text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.1);
  letter-spacing: 0.5rpx;
}

.user-message .message-text {
  color: rgba(255, 255, 255, 0.95);
}

.typing-cursor {
  display: inline-block;
  animation: blink 1s infinite;
  font-weight: bold;
  color: #ff6b9d;
  margin-left: 4rpx;
  vertical-align: middle;
}

@keyframes blink {
  0%,
  50% {
    opacity: 1;
  }
  51%,
  100% {
    opacity: 0;
  }
}

.input-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  width: 100%;
  background: rgba(28, 29, 48, 0.95);
  border-top: 1rpx solid rgba(255, 255, 255, 0.1);
  padding: 30rpx 40rpx;
  padding-bottom: calc(30rpx + env(safe-area-inset-bottom));
  z-index: 1001;
  box-sizing: border-box;
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
  box-shadow: 0 -10rpx 30rpx rgba(0, 0, 0, 0.25);
}

.input-wrapper {
  display: flex;
  gap: 25rpx;
  align-items: center;
  width: 100%;
  box-sizing: border-box;
  position: relative;
}

.message-input {
  flex: 1;
  padding: 20rpx 30rpx;
  border: 2rpx solid rgba(255, 255, 255, 0.2);
  border-radius: 40rpx;
  font-size: 32rpx;
  background: #2d2b39;
  box-sizing: border-box;
  height: 80rpx;
  color: rgba(255, 255, 255, 0.95);
  box-shadow: inset 0 2rpx 6rpx rgba(0, 0, 0, 0.2);
  transition: all 0.3s ease;
}

.message-input:focus {
  border-color: rgba(255, 107, 157, 0.5);
  background: #373545;
  box-shadow: inset 0 2rpx 8rpx rgba(0, 0, 0, 0.25), 0 0 15rpx rgba(255, 107, 157, 0.2);
}

.message-input:disabled {
  background: rgba(45, 43, 57, 0.5);
  color: rgba(255, 255, 255, 0.6);
  border-color: rgba(255, 255, 255, 0.1);
}

.input-placeholder {
  color: rgba(255, 255, 255, 0.4);
  font-size: 32rpx;
}

.send-button {
  padding: 0 35rpx;
  background: linear-gradient(135deg, #ff7b9c, #ff4281);
  color: white;
  border: none;
  border-radius: 40rpx;
  font-size: 32rpx;
  font-weight: 600;
  flex-shrink: 0;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  box-shadow: 0 8rpx 25rpx rgba(255, 66, 129, 0.4);
  letter-spacing: 1rpx;
  position: relative;
  overflow: hidden;
}

.send-button::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 50%;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 40rpx 40rpx 0 0;
  z-index: 0;
}

.send-button:active {
  transform: scale(0.95);
  box-shadow: 0 4rpx 10rpx rgba(255, 66, 129, 0.5);
}

.send-button:disabled {
  background: rgba(72, 67, 90, 0.7);
  border: 2rpx solid rgba(255, 255, 255, 0.2);
  color: rgba(255, 255, 255, 0.5);
  box-shadow: none;
}

.send-button:disabled::before {
  opacity: 0.1;
}

.send-text {
  font-size: 32rpx;
  font-weight: 600;
  white-space: nowrap;
  position: relative;
  z-index: 1;
  text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.2);
}
</style> 